﻿/* Copyright 2007-2008 dnAnalytics Project.
 *
 * Contributors to this file:
 * Jurgen Van Gael
 *
 * This file is part of dnAnalytics.  dnAnalytics is licensed under the 
 * Microsoft Public License. See License.txt for a complete copy of the
 * license.
 */

using System;
using CalcSharp.Core.Properties;

namespace dnAnalytics.Statistics.Distributions
{
    /// <summary>
    /// The Laplace distribution is a distribution over the real numbers parameterized by a mean and
    /// scale parameter. The pdf is
    /// 
    ///     p(x) = \frac{1}{2 * scale} \exp{- |x - mean| / scale}.
    /// </summary>
    /// <remarks>The distribution will use the <see cref="System.Random"/> by default. 
    /// Users can set the random number generator by using the <see cref="RandomNumberGenerator"/> property.
    /// 
    /// The statistics classes will check all the incoming parameters whether they are in the allowed
    /// range. This might involve heavy computation. Optionally, by setting Control.CheckDistributionParameters
    /// to false, all parameter checks can be turned off.</remarks>
    public class Laplace : IContinuousDistribution
    {
        // The mean of the normal distribution.
        private readonly double mMean;

        // The standard deviation of the normal distribution.
        private readonly double mScale;

        /// <summary>
        /// Constructs a standard Laplace (mean = 0, scale = 1).
        /// </summary>
        public Laplace() : this(0.0, 1.0)
        {
        }

        /// <summary>
        /// Constructs a Laplace distribution.
        /// </summary>
        /// <param name="mean">The mean for the normal distribution.</param>
        /// <param name="scale">The scale for the Laplace distribution.</param>
        /// <exception cref="ArgumentException">If <paramref name="scale"/> is negative.</exception>
        public Laplace(double mean, double scale)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(scale);
            }

            mMean = mean;
            mScale = scale;
            RandomNumberGenerator = new System.Random();
        }

        #region IDistribution Members

        /// <summary>
        /// The mean of the distribution.
        /// </summary>
        /// <value></value>
        public double Mean
        {
            get { return mMean; }
        }

        /// <summary>
        /// The standard deviation of the distribution.
        /// </summary>
        /// <value></value>
        public double StdDev
        {
            get { return System.Math.Sqrt(2.0)*mScale; }
        }

        /// <summary>
        /// The variance of the distribution.
        /// </summary>
        /// <value></value>
        public double Variance
        {
            get { return 2.0*mScale*mScale; }
        }

        /// <summary>
        /// The entropy of the distribution.
        /// </summary>
        /// <value></value>
        public double Entropy
        {
            get { return System.Math.Log(2.0*Math.Constants.E*mScale); }
        }

        /// <summary>
        /// Gets or sets the random number generator.
        /// </summary>
        /// <value>The random number generator used to generate a random sample.</value>
        public System.Random RandomNumberGenerator { get; set; }

        #endregion

        #region IContinuousDistribution Members

        /// <summary>
        /// The mode of the distribution.
        /// </summary>
        /// <value></value>
        public double Mode
        {
            get { return mMean; }
        }

        /// <summary>
        /// The median of the distribution.
        /// </summary>
        /// <value></value>
        public double Median
        {
            get { return mMean; }
        }

        /// <summary>
        /// Evaluates the probability density function for a the normal distribution.
        /// </summary>
        public double Density(double x)
        {
            return System.Math.Exp(-System.Math.Abs(x - mMean)/mScale)/(2.0*mScale);
        }

        /// <summary>
        /// Samples a Laplace distributed random variable.
        /// </summary>
        public double Sample()
        {
            return DoSample(RandomNumberGenerator, mMean, mScale);
        }

        /// <summary>
        /// Samples an array of Laplace distributed random variables.
        /// </summary>
        /// <param name="n">The number of variables needed.</param>
        public double[] Sample(int n)
        {
            return DoSample(RandomNumberGenerator, n, mMean, mScale);
        }

        #endregion

        /// <summary>
        /// Check the parameters of the distribution.
        /// </summary>
        /// <param name="scale">The scale of the Laplace distribution.</param>
        /// <exception cref="ArgumentOutOfRangeException">If the scale parameter is negative.</exception>
        private static void CheckParameters(double scale)
        {
            if (scale < 0.0)
            {
                throw new ArgumentOutOfRangeException("scale", Resources.ParameterCannotBeNegative);
            }
        }

        /// <summary>
        /// Evaluates the cumulative distribution function for the Laplace distribution.
        /// </summary>
        public double CumulativeDistribution(double x)
        {
            return 0.5*(1.0 + System.Math.Sign(x - mMean)*(1.0 - System.Math.Exp(-System.Math.Abs(x - mMean)/mScale)));
        }

        /// <summary>
        /// Evaluates the inverse cumulative distribution function for the Laplace distribution.
        /// </summary>
        public double InverseCumulativeDistribution(double x)
        {
            return mMean - mScale*System.Math.Sign(x - 0.5)*System.Math.Log(1.0 - 2.0*System.Math.Abs(x - 0.5));
        }

        /// <summary>
        /// Samples a Laplace distributed random variable.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="mean">The mean of the Laplace distribution.</param>
        /// <param name="scale">The scale of the Laplace distribution.</param>
        public static double Sample(System.Random rnd, double mean, double scale)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(scale);
            }

            return DoSample(rnd, mean, scale);
        }

        /// <summary>
        /// Samples an array of Laplace distributed random variables.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="n">The number of variables needed.</param>
        /// <param name="mean">The mean of the Laplace distribution.</param>
        /// <param name="scale">The scale of the Laplace distribution.</param>
        public static double[] Sample(System.Random rnd, int n, double mean, double scale)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(scale);
            }

            return DoSample(rnd, n, mean, scale);
        }

        private static double DoSample(System.Random rnd, double mean, double scale)
        {
            double u = rnd.NextDouble() - 0.5;
            return mean - scale*System.Math.Sign(u)*System.Math.Log(1.0 - 2.0*System.Math.Abs(u));
        }

        /// <summary>
        /// Samples an array of Laplace distributed random variables.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="n">The number of variables needed.</param>
        /// <param name="mean">The mean of the Laplace distribution.</param>
        /// <param name="scale">The scale of the Laplace distribution.</param>
        private static double[] DoSample(System.Random rnd, int n, double mean, double scale)
        {
            double[] arr = new double[n];
            for (int i = 0; i < n; i++)
            {
                arr[i] = DoSample(rnd, mean, scale);
            }
            return arr;
        }
    }
}